package com.library.ui;

import com.library.model.Book;
import com.library.service.BookService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class BookManagementPanel extends JPanel {
    private JTable bookTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private BookService bookService = new BookService();

    public BookManagementPanel() {
        setLayout(new BorderLayout());

        // 搜索栏
        searchField = new JTextField(20);
        JButton searchBtn = new JButton("模糊查询书名");
        searchBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String keyword = searchField.getText();
                List<Book> books = bookService.searchBooks(keyword);
                updateTable(books);
            }
        });
        JPanel searchPanel = new JPanel();
        searchPanel.add(new JLabel("搜索书名："));
        searchPanel.add(searchField);
        searchPanel.add(searchBtn);
        add(searchPanel, BorderLayout.NORTH);

        // 图书表格
        String[] columnNames = {"书号", "类别", "书名", "出版社", "作者", "价格", "总藏书量", "库存"};
        tableModel = new DefaultTableModel(columnNames, 0);
        bookTable = new JTable(tableModel);
        add(new JScrollPane(bookTable), BorderLayout.CENTER);

        // 操作按钮
        JButton addBtn = new JButton("新增图书");
        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addBookDialog();
            }
        });
        JButton updateBtn = new JButton("修改选中图书");
        updateBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateSelectedBook();
            }
        });
        JButton deleteBtn = new JButton("删除选中图书");
        deleteBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteSelectedBook();
            }
        });
        JPanel btnPanel = new JPanel();
        btnPanel.add(addBtn);
        btnPanel.add(updateBtn);
        btnPanel.add(deleteBtn);
        add(btnPanel, BorderLayout.SOUTH);

        // 初始化加载所有图书
        List<Book> books = bookService.getAllBooks();
        updateTable(books);
    }

    // 更新表格数据
    private void updateTable(List<Book> books) {
        tableModel.setRowCount(0);
        for (Book book : books) {
            tableModel.addRow(new Object[]{
                    book.getBookNumber(),
                    book.getCategory(),
                    book.getBookName(),
                    book.getPublisher(),
                    book.getAuthor(),
                    book.getPrice(),
                    book.getBookTotal(),
                    book.getInventory()
            });
        }
    }

    // 新增图书对话框
    private void addBookDialog() {
        JTextField bookNumberField = new JTextField();
        JTextField categoryField = new JTextField();
        JTextField bookNameField = new JTextField();
        JTextField publisherField = new JTextField();
        JTextField authorField = new JTextField();
        JTextField priceField = new JTextField();
        JTextField bookTotalField = new JTextField();
        JTextField inventoryField = new JTextField();

        JPanel panel = new JPanel(new GridLayout(8, 2));
        panel.add(new JLabel("书号："));
        panel.add(bookNumberField);
        panel.add(new JLabel("类别："));
        panel.add(categoryField);
        panel.add(new JLabel("书名："));
        panel.add(bookNameField);
        panel.add(new JLabel("出版社："));
        panel.add(publisherField);
        panel.add(new JLabel("作者："));
        panel.add(authorField);
        panel.add(new JLabel("价格："));
        panel.add(priceField);
        panel.add(new JLabel("总藏书量："));
        panel.add(bookTotalField);
        panel.add(new JLabel("库存："));
        panel.add(inventoryField);

        int result = JOptionPane.showConfirmDialog(null, panel, "新增图书", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try {
                String bookNumber = bookNumberField.getText();
                String category = categoryField.getText();
                String bookName = bookNameField.getText();
                String publisher = publisherField.getText();
                String author = authorField.getText();
                double price = Double.parseDouble(priceField.getText());
                int bookTotal = Integer.parseInt(bookTotalField.getText());
                int inventory = Integer.parseInt(inventoryField.getText());

                Book book = new Book(bookNumber, category, bookName, publisher, author, price, bookTotal, inventory);
                if (bookService.addBook(book)) {
                    JOptionPane.showMessageDialog(null, "图书添加成功");
                    List<Book> books = bookService.getAllBooks();
                    updateTable(books);
                } else {
                    JOptionPane.showMessageDialog(null, "图书添加失败，请检查输入");
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "价格、总藏书量和库存必须为数字");
            }
        }
    }

    // 修改选中图书信息
    private void updateSelectedBook() {
        int selectedRow = bookTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请选择要修改的图书");
            return;
        }

        String bookNumber = (String) tableModel.getValueAt(selectedRow, 0);
        Book book = bookService.getBookByNumber(bookNumber);

        JTextField categoryField = new JTextField(book.getCategory());
        JTextField bookNameField = new JTextField(book.getBookName());
        JTextField publisherField = new JTextField(book.getPublisher());
        JTextField authorField = new JTextField(book.getAuthor());
        JTextField priceField = new JTextField(String.valueOf(book.getPrice()));
        JTextField bookTotalField = new JTextField(String.valueOf(book.getBookTotal()));
        JTextField inventoryField = new JTextField(String.valueOf(book.getInventory()));

        JPanel panel = new JPanel(new GridLayout(7, 2));
        panel.add(new JLabel("类别："));
        panel.add(categoryField);
        panel.add(new JLabel("书名："));
        panel.add(bookNameField);
        panel.add(new JLabel("出版社："));
        panel.add(publisherField);
        panel.add(new JLabel("作者："));
        panel.add(authorField);
        panel.add(new JLabel("价格："));
        panel.add(priceField);
        panel.add(new JLabel("总藏书量："));
        panel.add(bookTotalField);
        panel.add(new JLabel("库存："));
        panel.add(inventoryField);

        int result = JOptionPane.showConfirmDialog(null, panel, "修改图书信息", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try {
                String category = categoryField.getText();
                String bookName = bookNameField.getText();
                String publisher = publisherField.getText();
                String author = authorField.getText();
                double price = Double.parseDouble(priceField.getText());
                int bookTotal = Integer.parseInt(bookTotalField.getText());
                int inventory = Integer.parseInt(inventoryField.getText());

                book.setCategory(category);
                book.setBookName(bookName);
                book.setPublisher(publisher);
                book.setAuthor(author);
                book.setPrice(price);
                book.setBookTotal(bookTotal);
                book.setInventory(inventory);

                if (bookService.updateBook(book)) {
                    JOptionPane.showMessageDialog(null, "图书信息修改成功");
                    List<Book> books = bookService.getAllBooks();
                    updateTable(books);
                } else {
                    JOptionPane.showMessageDialog(null, "图书信息修改失败，请检查输入");
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "价格、总藏书量和库存必须为数字");
            }
        }
    }

    // 删除选中图书
    private void deleteSelectedBook() {
        int selectedRow = bookTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请选择要删除的图书");
            return;
        }

        String bookNumber = (String) tableModel.getValueAt(selectedRow, 0);
        int confirm = JOptionPane.showConfirmDialog(null, "确定要删除该图书吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            if (bookService.deleteBook(bookNumber)) {
                JOptionPane.showMessageDialog(null, "图书删除成功");
                List<Book> books = bookService.getAllBooks();
                updateTable(books);
            } else {
                JOptionPane.showMessageDialog(null, "图书删除失败");
            }
        }
    }
}